package com.wanho.java156.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class SmsUtil {
    private static final Logger logger = Logger.getLogger(SmsUtil.class) ;
    @Value("${sms.url}")
    private String url ;

    @Value("${sms.uid}")
    private String uid ;

    @Value("${sms.key}")
    private String key ;

    @Value("${sms.encoding}")
    private String encoding ;

    public String send(String phone,String code){
        CloseableHttpResponse httpResponse = null ;
        try {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        /** HttpPost */
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("Uid", uid));
        params.add(new BasicNameValuePair("Key", key));
        params.add(new BasicNameValuePair("smsMob", phone));
        params.add(new BasicNameValuePair("smsText", "验证码:"+code));
        httpPost.setEntity(new UrlEncodedFormEntity(params, encoding));
        httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            String result = EntityUtils.toString(httpEntity, encoding);
            EntityUtils.consume(httpEntity);
            return result;
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                logger.info("## release resouce error ##" + e);
            }
        }
        return "短信发送异常" ;
    }

}
